package com.wswy.wzcx.ui.fkdj

import android.Manifest
import android.app.Activity
import android.app.DatePickerDialog
import android.arch.lifecycle.Observer
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.*
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.utils.ToastUtils
import com.facebook.drawee.view.SimpleDraweeView
import com.google.zxing.activity.CaptureActivity
import com.google.zxing.util.QrConstant
import com.tbruyelle.rxpermissions2.RxPermissions
import com.wswy.wzcx.R
import com.wswy.wzcx.api.ConfigsKt
import com.wswy.wzcx.model.PaymentOrder
import com.wswy.wzcx.model.home.RPaths
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.module.InternalMsgCode
import com.wswy.wzcx.module.base.*
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ModuleActivity
import com.wswy.wzcx.ui.coupon.ChooseCouponFragment
import com.wswy.wzcx.ui.dialog.WarningDialog
import com.wswy.wzcx.ui.fragment.WZDBFragment
import com.wswy.wzcx.ui.other.DialogFactory
import com.wswy.wzcx.ui.other.FineNoTextWatcher
import com.wswy.wzcx.ui.other.PayControl
import com.wswy.wzcx.ui.other.TextWatcherIMPL
import com.wswy.wzcx.ui.pay.PayOrder
import com.wswy.wzcx.ui.pay.PayOrderFragment
import com.wswy.wzcx.ui.pay.PreFineInfo
import com.wswy.wzcx.ui.web.WebViewActivity
import com.wswy.wzcx.utils.FileUtils
import com.wswy.wzcx.utils.FrescoUtils
import com.wswy.wzcx.utils.ImageUtils
import com.wswy.wzcx.utils.StringUtils
import com.wswy.wzcx.widget.utils.MoneyTextWatcher
import com.wzcx.orclib.PhotoAgent
import io.reactivex.SingleObserver
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_fine_order.*
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.*

class FineOrderFragment : CBaseFragment() {


    private lateinit var fineViewModel: FineViewModel

    private var inputLayout: View? = null //无法识别 手动输入
    private var detailLayout: View? = null //识别成功


    private var lastQueryNo: String? = null

    private companion object {
        private const val REQ_CHOOSE_PHOTO = 71
    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_fine_order
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        fineViewModel = provideViewModel(FineViewModel::class.java)
        initView()
    }


    private fun initView() {
        fj_wz_txt.apply {
            fj_wz_txt.text = SpannableStringBuilder()
            append("收到告知单请前往")
            append(SpannableString("违章代办>").apply {
                setSpan(ForegroundColorSpan(getColor(R.color.endColor_1)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })
        }
        fj_wz_txt.onClick {
            startActivity(ModuleActivity.getTargetIntent(it.context, WZDBFragment.TAG).apply {
            })
        }
        et_fine_no.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(19))
        et_fine_no.addTextChangedListener(FineNoTextWatcher(et_fine_no))
        et_fine_no.addTextChangedListener(object : TextWatcherIMPL() {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                super.onTextChanged(s, start, before, count)
                if (TextUtils.isEmpty(s)) {
                    //为空 扫描
                    img_input.setImageResource(R.drawable.scanning)
                    //fl_no_clear.visibility = View.INVISIBLE
                } else {
                    //不为空 删除
                    img_input.setImageResource(R.drawable.ic_clean)
                    //fl_no_clear.visibility = View.VISIBLE
                }
                notifyNextQuery()
            }
        })

        fineViewModel.getLastFineNo()?.let {
            kotlin.runCatching {
                et_fine_no.setText(it)
                et_fine_no.setSelection(et_fine_no.text?.length ?: 0)
            }

        }


        KeyboardUtils.registerSoftInputChangedListener(requireActivity()) {
            Timber.e("----$it")

            if (fineViewModel.hasLogin() && it == 0 && (detailLayout != null || inputLayout != null)) {
                val no = FineNoTextWatcher.getRealFineNumber(et_fine_no)
                if (!no.isNullOrEmpty() && no.length >= 15 && !TextUtils.equals(no, lastQueryNo)) {
                    fineViewModel.checkFine2(no, null)
                    ll_btn_next.isClickable = false
                }
            }

        }

        fl_no_clear.onClick {
            //
            if (TextUtils.isEmpty(et_fine_no.text)) {
                //扫描
                RxPermissions(this).request(Manifest.permission.CAMERA).singleOrError()
                        .subscribe(object : SingleObserver<Boolean> {
                            override fun onSuccess(t: Boolean) {
                                if (t) {
                                    val intent = Intent(requireContext(), CaptureActivity::class.java).apply {
                                        putExtra(QrConstant.CONFIG_TITLE, "扫描处罚决定书编号")
                                    }
                                    startActivityForResult(intent, QrConstant.REQ_QR_CODE)
                                } else {
                                    ToastUtils.showText("没有权限")
                                }
                            }

                            override fun onSubscribe(d: Disposable) {

                            }

                            override fun onError(e: Throwable) {
                                ToastUtils.showText(e.message)
                            }

                        })


            } else {
                //删除
                et_fine_no.text = null
                fineViewModel.saveFineNo(null)
            }

        }

        tv_no_hint.onClick {
            DialogFactory.showHelp(it.context, R.drawable.chujuebianma)
        }

        tv_issue.onClick {
            WebViewActivity.startWebview(it.context, ConfigsKt.H5_CJWT_FKDJ())
        }

        var login = false

        ll_btn_next.isEnabled = true
        ll_btn_next.isClickable = true
        ll_btn_next.onClick {
            (it.getTag(R.id.item_data) as? PreFineInfo)?.let {
                //直接下一步
                RouterUtils.startPage(requireActivity(), RPaths.PAY_ORDER, Bundle().apply {
                    putParcelable(Constants.EXTRA_DATA, PayOrder(PayOrder.TYPE_FKDJ, it))
                })

                Timber.e("----$it")
                return@onClick
            }

            //点击下一步
            val no = FineNoTextWatcher.getRealFineNumber(et_fine_no)

            Timber.e("---- ${inputLayout?.isShown}     ${detailLayout?.isShown}")

            login = false
            var inputed: PreFineInfo? = null
            // 输入服务费
            if (TextUtils.equals(lastQueryNo, no) && inputLayout?.isShown == true) {
                //服务费 等
                inputed = (inputLayout?.getTag(R.id.item_view_holder) as? InputViewHolder)?.getPreFineInfo()
            }

            if (fineViewModel.checkFineNo(no, inputed)) {

                if (fineViewModel.hasLogin()) {
                    fineViewModel.checkFine2(no!!, inputed)
                    ll_btn_next.isClickable = false
                } else {
                    fineViewModel.gotoLogin(it.context)
                    login = true
                }
            }
        }

        //填充默认处罚决定书单号
        arguments?.getString(Constants.EXTRA_DATA)?.let {
            et_fine_no.setText(it)
            et_fine_no.setSelection(et_fine_no.text?.length ?: 0)
        }

        fineViewModel.getUserLiveData().observe(this, Observer {
            it?.run {

                val no = FineNoTextWatcher.getRealFineNumber(et_fine_no)
                if (login && fineViewModel.checkFineNo(no)) {
                    fineViewModel.checkFine(no!!)
                }
            }
        })

        fineViewModel.getPreFineInfoLiveData().observe(this, Observer {

            it?.run {
                if (inLoading()) {
                    lockInput()
                    ll_btn_next.loading("识别中")
                } else {
                    unlockInput()
                    val resp = data
                    if (isOk() && resp != null) {
                        //识别成功
                        showQueryEnd(resp)
                    } else {
                        //识别失败
                        showQueryEnd(null)
                    }

                }
            }

        })


        registerEvent(InternalMsgCode.CODE_PAY_SUCCESS) {
            finish()
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)


        if (resultCode == Activity.RESULT_OK && requestCode == REQ_CHOOSE_PHOTO) {
            val saveFile = FileUtils.getSaveFile(context)

            if (saveFile.exists()) {
                FrescoUtils.removeCache(Uri.fromFile(saveFile))

                if (inputLayout?.parent != null) {
                    Timber.e("-----" + saveFile)
                    (inputLayout?.getTag(R.id.item_view_holder) as? InputViewHolder)?.let {
                        ImageUtils.showImage(it.imgAdd, saveFile)

                        it.imgAdd.setTag(R.id.item_data, saveFile.absolutePath)

                        //图片
                        notifyNextQuery()
                    }
                }
            }
        }
    }


    private fun notifyNextQuery() {
        ll_btn_next.normal("罚单查询")
        ll_btn_next.setTag(R.id.item_data, null)
    }


    private fun lockInput() {
        et_fine_no.isEnabled = false
        et_fine_no.isClickable = false
        ll_btn_next.isClickable = false
        fl_no_clear.isClickable = false
    }

    private fun unlockInput() {
        et_fine_no.isEnabled = true
        et_fine_no.isClickable = true
        ll_btn_next.isClickable = true
        fl_no_clear.isClickable = true
    }

    private fun showQueryEnd(fine: PreFineInfo?) {
        //成功
        ll_btn_next.end("下一步") {
            //非首次查询
            if (fineViewModel.fineQueryCount <= 1) {
                //首次查询，修改布局
                //移除底部的流程提示和修改下一步按钮位置
                showFirstReLayout()
            }

            if (fine != null) {
                if (fine.cheCarData == true) {
                    showQueryDetail(fine)

                } else {
                    showInputLayout(fine)
                }

                //提示
                fine.abnormalAreaHint?.trim()?.let {
                    if (it.isNotEmpty()) {
                        WarningDialog(requireContext(), it).show()
                    }
                }

                lastQueryNo = fine.fineNo
            }

        }
    }

    //显示正确的查询结果
    private fun showQueryDetail(fine: PreFineInfo) {
        val layout = fl_fine_info_container
        tv_query_title.visible()
        layout.visible()

        tv_query_title.text = "请确认以下信息"
        //查询成功
        ll_btn_next.normal("下一步")
        ll_btn_next.setTag(R.id.item_data, fine)
        ToastUtils.showText("查询成功，请点击下一步")

        layout.removeAllViews()

        if (detailLayout == null) {
            detailLayout = LayoutInflater.from(layout.context).inflate(R.layout.layout_fine_query_detail, layout, false)
            detailLayout?.let {
                val viewHolder = DetailViewHolder(
                        et_fine_no,
                        it.findViewById(R.id.tv_car_no),
                        it.findViewById(R.id.tv_fine_name),
                        it.findViewById(R.id.tv_fine_date),
                        it.findViewById(R.id.tv_fine_fee),
                        it.findViewById(R.id.tv_fine_late_fee)
                )

                viewHolder.tvFineLateAmount.onClick {
                    showLateFeeDialog()
                }

                it.setTag(R.id.item_view_holder, viewHolder)
            }
        }

        detailLayout?.let {

            //先移除
            (it.parent as? ViewGroup)?.removeViewInLayout(it)

            (it.getTag(R.id.item_view_holder) as? DetailViewHolder)?.let {

                it.tvCarNo.text = fine.carNo
                it.tvFineName.text = fine.fineName
                it.tvFineDate.text = fine.fineDate
                it.tvFineFee.text = getString(R.string.amount_args, StringUtils.formatMoney(fine.fineFee?.toDouble()
                        ?: 0.0))

                if (fine.fineLateFee?.toDouble() ?: 0.0 > 0.0) {
                    it.tvFineLateAmount.visible()
                    it.tvFineLateAmount.text = "滞纳金 " + getString(R.string.amount_args, StringUtils.formatMoney(fine.fineLateFee?.toDouble()
                            ?: 0.0))
                } else {
                    it.tvFineLateAmount.gone()
                }

            }

            layout.addView(it)
        }
    }

    //罚单查询不到，显示输入
    private fun showInputLayout(fine: PreFineInfo) {
        val layout = fl_fine_info_container
        tv_query_title.visible()
        layout.visible()
        tv_query_title.apply {
            text = "注意：交管数据连接失败，未能成功获取罚单信息，继续提交需要手动输入以下内容"
            setTextColor(getColor(R.color.accentColor3))
            setPadding(SizeUtils.dp2px(8f), SizeUtils.dp2px(5f), SizeUtils.dp2px(8f), SizeUtils.dp2px(5f))
        }
        tv_query_title.setBackgroundColor(getColor(R.color.red_bg_color))
        layout.removeAllViews()
        ll_btn_next.normal("罚单查询")
        if (inputLayout == null) {
            inputLayout = LayoutInflater.from(layout.context).inflate(R.layout.layout_fine_input_detail, layout, false)

            inputLayout?.let {


                val viewHolder = InputViewHolder(
                        et_fine_no,
                        it.findViewById(R.id.et_fine_name),
                        it.findViewById(R.id.tv_fine_date),
                        it.findViewById(R.id.et_fine_fee),
                        it.findViewById(R.id.tv_fine_late_fee),
                        it.findViewById(R.id.img_add)
                )

                viewHolder.etFineName.addTextChangedListener(object : TextWatcherIMPL() {
                    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                        super.onTextChanged(s, start, before, count)
                        notifyNextQuery()
                        //隐藏滞纳金
                        viewHolder.tvFineLateAmount.gone()
                    }
                })

                viewHolder.tvFineLateAmount.onClick {
                    showLateFeeDialog()
                }

                //日期
                viewHolder.tvFineDate.onClick {
                    showChooseDate()
                }

                //金额
                viewHolder.etFineFee.run {
                    addTextChangedListener(MoneyTextWatcher())
                    addTextChangedListener(object : TextWatcherIMPL() {
                        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                            super.onTextChanged(s, start, before, count)
                            notifyNextQuery()
                        }
                    })
                    inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
                }
                //选择图片
                viewHolder.imgAdd.onClick {
                    startActivityForResult(PhotoAgent.getPhotoIntent(context, FileUtils.getSaveFile(context).getAbsolutePath(), null), REQ_CHOOSE_PHOTO)
                }

                it.setTag(R.id.item_view_holder, viewHolder)

            }

        }

        inputLayout?.let {
            // 没有显示 显示移除旧的 再添加
            if (!it.isShown) {
                (it.parent as? ViewGroup)?.removeViewInLayout(it)
                layout.addView(it)
            }

            (it.getTag(R.id.item_view_holder) as? InputViewHolder)?.let {
                //绑定数据
                val no = FineNoTextWatcher.getRealFineNumber(it.etFineNo)
                val lastFineNo = lastQueryNo
                val currFine = it.getPreFineInfo()

                if (TextUtils.equals(no, lastFineNo) && no.length >= 15 && fine.fineNo?.length ?: 0 >= 15 && TextUtils.equals(no.subSequence(0, 15), fine.fineNo?.subSequence(0, 15))) {
                    //前15位一致
                    //当前处罚时间和处罚金额 一致
                    if (currFine.fineDate == fine.fineDate && currFine.fineFee == fine.fineFee && currFine.fineName == fine.fineName) {

                        if (fine.fineLateFee?.toDouble() ?: 0.0 > 0.0) {
                            it.tvFineLateAmount.visible()
                            it.tvFineLateAmount.text = "滞纳金 " + getString(R.string.amount_args, StringUtils.formatMoney(fine.fineLateFee?.toDouble()
                                    ?: 0.0))

                        } else {
                            it.tvFineLateAmount.gone()
                        }

                        //查询结果保持一致
                        ll_btn_next.normal("下一步")
                        ll_btn_next.setTag(R.id.item_data, fine)
                        ToastUtils.showText("查询成功，请点击下一步")
                    }

                } else {
                    //重置
                    it.etFineName.setText("")
                    it.tvFineDate.setText("")
                    it.etFineFee.setText("")

                    it.imgAdd.setActualImageResource(R.drawable.fine_take_photo)
                    it.imgAdd.setTag(R.id.item_data, null)

                    it.tvFineLateAmount.gone()
                }
            }
        }
    }


    private fun showFirstReLayout() {
        //首次显示 更新控件位置
        //移除提示
//        view?.findViewById<LinearLayout>(R.id.layout_fkdj_tips)?.let {
//            (view as? ViewGroup)?.removeView(it)
//        }
        layout_fkdj_tips.gone()
        //将按钮更新到最下面
        val btn = ll_btn_next
        if (btn.parent !== view) {
            rl_top_input.removeView(btn)
            btn.setBackgroundResource(R.drawable.common_btn_background)
            //移到最下面
            (view as? ViewGroup)?.addView(btn, RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(54f)).apply {
                addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
            })

            //修改内容
            (scroll_view.layoutParams as? RelativeLayout.LayoutParams)?.let {
                it.addRule(RelativeLayout.ABOVE, R.id.ll_btn_next)
                scroll_view.layoutParams = it
            }
        }
    }

    private var chooseCalendar: Calendar? = null
    private val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    private fun showChooseDate() {
        val context = context
        val calendar = Calendar.getInstance()

        var year = Math.max(calendar.get(Calendar.YEAR), 2019)
        var month = 0
        var dayOfM = 1

        chooseCalendar?.run {
            year = get(Calendar.YEAR)
            month = get(Calendar.MONTH)
            dayOfM = get(Calendar.DAY_OF_MONTH)
        }


        val datePickerDialog = DialogFactory.createDatePickerDialog(context, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
            if (chooseCalendar == null) {
                chooseCalendar = Calendar.getInstance()
            }
            chooseCalendar?.run {
                set(Calendar.YEAR, year)
                set(Calendar.MONTH, month)
                set(Calendar.DAY_OF_MONTH, dayOfMonth)

                val date = format.format(time)

                if (inputLayout?.isShown == true) {
                    (inputLayout?.getTag(R.id.item_view_holder) as? InputViewHolder)?.let {
                        it.tvFineDate.text = date

                        //日期改变
                        notifyNextQuery()
                    }
                }
            }

        }, year, month, dayOfM)
        val datePicker = datePickerDialog.datePicker
        datePicker.maxDate = calendar.timeInMillis
        datePickerDialog.show()
    }


    private fun showLateFeeDialog() {
        //显示滞纳金提示
        WarningDialog(requireContext(), getString(R.string.late_fee_msg)).apply {
            title = "什么是滞纳金？"
        }.show()

    }


    //////
    private interface IFineView {
        fun getPreFineInfo(): PreFineInfo
    }

    private class InputViewHolder(val etFineNo: EditText,
                                  val etFineName: EditText,
                                  val tvFineDate: TextView,
                                  val etFineFee: EditText,
                                  val tvFineLateAmount: TextView,
                                  val imgAdd: SimpleDraweeView
    ) : IFineView {

        override fun getPreFineInfo(): PreFineInfo {
            val no = FineNoTextWatcher.getRealFineNumber(etFineNo)

            return PreFineInfo(no, null,
                    etFineName.text?.toString(),
                    tvFineDate.text?.toString(),
                    etFineFee.text?.toString(),
                    fineLateFee = tvFineLateAmount.text?.toString(),
                    img = imgAdd.getTag(R.id.item_data)?.toString()
            )
        }

    }

    private class DetailViewHolder(val etFineNo: EditText,
                                   val tvCarNo: TextView,
                                   val tvFineName: TextView,
                                   val tvFineDate: TextView,
                                   val tvFineFee: TextView,
                                   val tvFineLateAmount: TextView
    ) : IFineView {
        override fun getPreFineInfo(): PreFineInfo {
            val no = FineNoTextWatcher.getRealFineNumber(etFineNo)
            return PreFineInfo(no,
                    null,
                    tvFineName.text?.toString(),
                    tvFineDate.text?.toString(),
                    tvFineFee.text?.toString(),
                    fineLateFee = tvFineLateAmount.text?.toString(),
                    cheCarData = true
            )
        }
    }

}